package org.csu.mypetstore.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.csu.mypetstore.api.common.CommonResponce;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import org.csu.mypetstore.api.common.ResponseCode;
import org.csu.mypetstore.api.entity.*;
import org.csu.mypetstore.api.persistence.*;
import org.csu.mypetstore.api.service.AccountService;
import org.csu.mypetstore.api.service.CartService;
import org.csu.mypetstore.api.service.OrderService;
import org.csu.mypetstore.api.vo.AccountVO;
import org.csu.mypetstore.api.vo.OrderVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/*import java.lang.classfile.instruction.LineNumber;*/
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private SequenceMapper sequenceMapper;
    @Autowired
    private LineItemMapper lineItemMapper;
    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private AccountService accountService; // 需要实现账户服务
    @Autowired
    private CartService cartService; // 需要实现购物车服

    @Transactional
    @Override
    public CommonResponce<OrderVO> createOrder(String username, OrderRequest orderRequest) {
        try {

            // 1. 获取用户的所有购物车项（按linenum排序）
            QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("userid", username)
                    .orderByAsc("linenum"); // 按购物车项的序号排序
            List<Cart> cartItems = cartMapper.selectList(queryWrapper);
           if (cartItems.isEmpty()) {
                return CommonResponce.createForError("购物车是空的");
            }

            // 构建订单基础信息
            Account account = accountMapper.selectById(username);
            OrderVO orderVO = buildOrderFromAccountAndCart(account, orderRequest, cartItems);

            // 生成序列号（返回int）
            int rawOrderId = getNextId("ordernum");
            orderVO.setOrderId(rawOrderId);

            // 插入订单
            orderMapper.insert(convertToEntity(orderVO));

            // 保存订单明细
            saveLineItems(rawOrderId, cartItems);

            // 7. 清空购物车（按业务需求决定）
            /*cartService.clearCart(username);*/

            return CommonResponce.createForSuccessMessage(0,"订单创建成功",orderVO);

        } catch (Exception e) {
            return CommonResponce.createForError("订单创建失败");
        }
    }



    // 核心初始化方法
    private OrderVO buildOrderFromAccountAndCart(Account account, OrderRequest request, List<Cart> cartItems) {
        OrderVO orderVO = new OrderVO();

        // 账户信息注入
        orderVO.setUserid(account.getUserid());
        orderVO.setOrderdate(new Date());

        // 配送信息
        orderVO.setShipaddr1(request.getShipTo().getAddress1());
        orderVO.setShipaddr2(request.getShipTo().getAddress2());
        orderVO.setShipcity(request.getShipTo().getCity());
        orderVO.setShipstate(request.getShipTo().getState());
        orderVO.setShipzip(request.getShipTo().getZip());
        orderVO.setShipcountry(request.getShipTo().getCountry());
        orderVO.setShiptofirstname(request.getShipTo().getFirstName());
        orderVO.setShiptolastname(request.getShipTo().getLastName());

        // 账单信息（根据需求决定是否与配送地址分开）
        orderVO.setBilladdr1(request.getShipTo().getAddress1());
        orderVO.setBilladdr2(request.getShipTo().getAddress2());
        orderVO.setBillcity(request.getShipTo().getCity());
        orderVO.setBillstate(request.getShipTo().getState());
        orderVO.setBillzip(request.getShipTo().getZip());
        orderVO.setBillcountry(request.getShipTo().getCountry());
        orderVO.setBilltofirstname(request.getShipTo().getFirstName());
        orderVO.setBilltolastname(request.getShipTo().getLastName());

        // 支付信息（建议走支付系统，这里保持原有逻辑）
        orderVO.setCreditcard(request.getCreditcard());
        orderVO.setExprdate(request.getExprdate());
        orderVO.setCardtype(request.getCardType());
        orderVO.setCourier("UPS");
        orderVO.setLocale("CA");
        orderVO.setStatus("P");



        // 计算总价
        orderVO.setTotalprice(calculateTotalPrice(cartItems));

        return orderVO;
    }

    // 计算订单总价
    private BigDecimal calculateTotalPrice(List<Cart> cartItems) {
        BigDecimal total = BigDecimal.ZERO;
        for (Cart item : cartItems) {
            BigDecimal itemTotal = item.getUnitprice().multiply(BigDecimal.valueOf(item.getQuantity()));
            total = total.add(itemTotal);
        }
        return total;
    }

    // 保存订单明细
    // 修改后的方法：按购物车项的linenum保存订单明细
    private void saveLineItems(int orderId, List<Cart> cartItems) {
        int linnumber=1;
        for (Cart cartItem : cartItems) {
            LineItem lineItem = new LineItem();
            lineItem.setOrderId(orderId);
            lineItem.setLineNumber(linnumber++); // 直接使用购物车项的序号
            lineItem.setItemId(cartItem.getItemid());
            lineItem.setQuantity(cartItem.getQuantity());
            lineItem.setUnitPrice(cartItem.getUnitprice());
            lineItemMapper.insert(lineItem);
        }
    }

    @Override
    public CommonResponce<OrderVO> getOrder(String username, String orderId) {
        try {
            OrderVO order = orderMapper.selectOrderWithItemsById(Integer.parseInt(orderId));
            if (order == null || !order.getUserid().equals(username)) {
                // 使用带状态码和消息的工厂方法
                return CommonResponce.createForError(ResponseCode.ILLEGAL_ARGUMENT.getCode(), "订单不存在");
            }
            return CommonResponce.createForSuccess(order);
        } catch (Exception e) {
            return CommonResponce.createForError("服务器异常");
        }
    }

    @Override
    public CommonResponce<List<OrderVO>> getOrders(String username) {
        try {

            List<OrderVO> orders = orderMapper.selectOrdersWithItemsByUserId(username);
            if (orders.isEmpty()) {
                // 使用带状态码的成功响应（消息在前端显示）
                return CommonResponce.createForSuccessMessage("该用户还没有订单");
            }
            return CommonResponce.createForSuccessMessage(0,"success",orders);
        } catch (Exception e) {
                return CommonResponce.createForError("服务器异常");
        }
    }

    /**
     * 获取下一个序列号（带锁保证线程安全）
     */
    @Transactional
    public synchronized int getNextId(String name) {
        // 1. 获取并锁定序列记录
        Sequence sequence = sequenceMapper.getSequenceForUpdate(name);
        if (sequence == null) {
            throw new RuntimeException("Sequence not found: " + name);
        }

        // 2. 获取当前值
        int currentId = sequence.getNextId();

        // 3. 更新序列值
        sequence.setNextId(currentId + 1);
        sequenceMapper.updateNextId(name, sequence.getNextId());

        return currentId; // 返回未格式化的整数值
    }

    private Order convertToEntity(OrderVO vo) {
        Order entity = new Order();
        // 基础信息
        entity.setOrderId(vo.getOrderId());
        entity.setUserid(vo.getUserid());
        entity.setOrderdate(vo.getOrderdate());

        // 配送地址信息
        entity.setShipaddr1(vo.getShipaddr1());
        entity.setShipaddr2(vo.getShipaddr2());
        entity.setShipcity(vo.getShipcity());
        entity.setShipstate(vo.getShipstate());
        entity.setShipzip(vo.getShipzip());
        entity.setShipcountry(vo.getShipcountry());

        // 账单地址信息
        entity.setBilladdr1(vo.getBilladdr1());
        entity.setBilladdr2(vo.getBilladdr2());
        entity.setBillcity(vo.getBillcity());
        entity.setBillstate(vo.getBillstate());
        entity.setBillzip(vo.getBillzip());
        entity.setBillcountry(vo.getBillcountry());

        // 物流信息
        entity.setCourier(vo.getCourier());

        // 财务信息
        entity.setTotalprice(vo.getTotalprice());

        // 账单联系人
        entity.setBilltolastname(vo.getBilltolastname());
        entity.setBilltofirstname(vo.getBilltofirstname());

        // 配送联系人
        entity.setShiptofirstname(vo.getShiptofirstname());
        entity.setShiptolastname(vo.getShiptolastname());

        // 支付信息
        entity.setCreditcard(vo.getCreditcard());
        entity.setExprdate(vo.getExprdate());
        entity.setCardtype(vo.getCardtype());

        // 区域信息
        entity.setLocale(vo.getLocale());

        return entity;
    }
}
